//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "HotSearchViewController.h"
#import "RestaurantDetailViewController.h"
#import "LoadMoreCell.h"
#import "SearchCell.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "config.h"
#import "OMGToast.h"
#import "MapResultViewController.h"
#import "CardCell.h"
#import "CardDetailViewController.h"
#import "TicketCell.h"
#import "TicketDetailViewController.h"
@interface HotSearchViewController ()

@end

@implementation HotSearchViewController
@synthesize lbAddress;
@synthesize btCuisine;
@synthesize mainTable;
@synthesize reqArea;
@synthesize reqCuisine;
@synthesize reqSearch;
@synthesize reqSearchMore;
@synthesize arrayDistrict;
@synthesize arrayCuisineType;
@synthesize arrayConsume;
@synthesize reqConsume;
@synthesize arrayType;
@synthesize areaId;
- (void)viewDidLoad
{
    [super viewDidLoad];
    
	// Do any additional setup after loading the view, typically from a nib.
    wqTable = mainTable;
    _iViewMerchantType=MERCHANTALL;
    pageIndex=1;
    lbAddress.text = [[Config Instance]getLocation];
    
    cuisineId = 0;
    arrayType= [[NSMutableArray alloc] initWithObjects:
                [NSDictionary dictionaryWithObjectsAndKeys:@"餐饮",@"arrayType",nil],
                [NSDictionary dictionaryWithObjectsAndKeys:@"KTV",@"arrayType",nil],
                [NSDictionary dictionaryWithObjectsAndKeys:@"咖啡茶馆",@"arrayType",nil],
                nil];
    arrayTypeTicket= [[NSMutableArray alloc] initWithObjects:
                      [NSDictionary dictionaryWithObjectsAndKeys:@"全部",@"arrayTypeTicket",nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"餐饮",@"arrayTypeTicket",nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"KTV",@"arrayTypeTicket",nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"咖啡茶馆",@"arrayTypeTicket",nil],
                      nil];
    arrayScore= [[NSMutableArray alloc] initWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:@"全部",@"arrayScore",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"[5-4]分",@"arrayScore",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"[4-3]分",@"arrayScore",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"[3-2]分",@"arrayScore",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"[2-1]分",@"arrayScore",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"无评分",@"arrayScore",nil],
                 nil];
    arrayMerchant= [[NSMutableArray alloc] initWithObjects:
                    [NSDictionary dictionaryWithObjectsAndKeys:@"全部商户",@"arrayMerchant",nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"会员卡商户",@"arrayMerchant",nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"优惠券商户",@"arrayMerchant",nil],
                    nil];
    arrayOrderBy= [[NSMutableArray alloc] initWithObjects:
                   [NSDictionary dictionaryWithObjectsAndKeys:@"离我最近",@"arrayOrderBy",nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"评分最高",@"arrayOrderBy",nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"人气最高",@"arrayOrderBy",nil],
                   nil];
    _selectedIndex4=0;
    typeId=1;
    if(_iHotType==HOTCARD)
    {
        [_BtnType setTitle:@"会员卡" forState:UIControlStateNormal];
        _BtnType.imageView.hidden=YES;
        _BtnType.userInteractionEnabled=NO;
        [_BtnType removeTarget:self action:@selector(OnClickType:) forControlEvents:UIControlEventTouchUpInside];
        _lbThird.text=@"离我最近";
        [_btnThird removeTarget:self action:@selector(showCuisine:) forControlEvents:UIControlEventTouchUpInside];
        [_btnThird addTarget:self action:@selector(showOrderBy:) forControlEvents:UIControlEventTouchUpInside];
        [arrayOrderBy removeLastObject];
        orderByType=1;
    }
    else if(_iHotType==HOTTICKET)
    {
        [_BtnType setTitle:@"优惠券" forState:UIControlStateNormal];
        _BtnType.imageView.hidden=YES;
        _BtnType.userInteractionEnabled=NO;
        [_BtnType removeTarget:self action:@selector(OnClickType:) forControlEvents:UIControlEventTouchUpInside];
        _lbThird.text=@"人气最高";
        [_btnThird removeTarget:self action:@selector(showCuisine:) forControlEvents:UIControlEventTouchUpInside];
        [_btnThird addTarget:self action:@selector(showOrderBy:) forControlEvents:UIControlEventTouchUpInside];
        orderByType=3;
        _selectedIndex6=2;
        typeId=0;
        _lbFirst.text=@"全部";
        [_btnFirst removeTarget:self action:@selector(showType:) forControlEvents:UIControlEventTouchUpInside];
        [_btnFirst addTarget:self action:@selector(showTypeTicket:) forControlEvents:UIControlEventTouchUpInside];
    }
    if(areaId != 0 ){
        if(_areaName !=NULL){
            _lbSecond.text = _areaName;
        }
    }
    
    [self startRequest];
    
    // [self getCounsume];
    
}

- (void)showLoadingView
{
    }
- (void)startRequest
{
    // [loadingView setActivityViewColor:[UIColor blueColor]];
    if (!loadingView) {
        
        loadingView = [[RequestLoadingView alloc]
                       initRequestLoadingView:self
                       queueFinishSelector:@selector(stopLoadingView)
                       viewFrame:LoadingViewFrame];
    }
    
    [self getSearchResult];
    [self getArea];
    [self getCuisine];
    
    [loadingView addRequestToQueue:reqSearch];
    [loadingView addRequestToQueue:reqArea];
    [loadingView addRequestToQueue:reqCuisine];
    
    [loadingView startRequestQueue];
    
    NSLog(@"scree %f",MainScreenHeight);
}

-(void)viewWillAppear:(BOOL)animated
{
    
    if(_iHotType==HOTCARD)
    {
        if(self.view.tag==1)
        {
            [OMGToast showWithText:@"该会员卡已关闭" bottomOffset:100];
            self.view.tag=0;
        }
    }
    else if(_iHotType==HOTTICKET)
    {
        if(self.view.tag==1)
        {
            [OMGToast showWithText:@"该优惠券已关闭" bottomOffset:100];
            self.view.tag=0;
        }
    }
}

- (void) getSearchResult{
    @try {
        //异步请求
        if(_iHotType==HOTHOT || _iHotType==HOTRECOMMAND)
        {
            NSURL *url = [NSURL URLWithString:_iHotType==HOTHOT?url_hotList:url_recommandList];
            reqSearch=[ASIFormDataRequest requestWithURL:url];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",pageIndex] forKey:@"pageIndex"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance]getCityId]] forKey:@"cityID"];
            if (cuisineId != 0 && typeId==1)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",cuisineId] forKey:@"cuisineID"];
            if (areaId != 0)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",areaId] forKey:@"areaID"];
            if(avgConsumeID != 0 && typeId==1)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",avgConsumeID] forKey:@"avgConsumeID"];
            if(typeId!=1 && score!=0)
            {
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",score] forKey:@"score"];
            }
            if(_iViewMerchantType==MERCHANTCARD)
            {
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",1] forKey:@"isCard"];
            }
            else if(_iViewMerchantType==MERCHANTTICKET)
            {
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",1] forKey:@"isCoupon"];
            }
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",typeId] forKey:@"merchantType"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
        }
        else if(_iHotType==HOTCARD)
        {
            NSURL *url = [NSURL URLWithString:url_cardList];
            reqSearch=[ASIFormDataRequest requestWithURL:url];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",pageIndex] forKey:@"pageIndex"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance]getCityId]] forKey:@"cityID"];
            if (cuisineId != 0 && typeId==1)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",cuisineId] forKey:@"cuisineID"];
            if (areaId != 0)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",areaId] forKey:@"areaID"];
            if(avgConsumeID != 0 && typeId==1)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",avgConsumeID] forKey:@"avgConsumeID"];
            if(typeId!=1 && score!=0)
            {
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",score] forKey:@"score"];
            }
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",typeId] forKey:@"merchantType"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",orderByType] forKey:@"orderBy"];
            //[reqSearch setPostValue:@"31.853357" forKey:@"latitude"];
            //[reqSearch setPostValue:@"117.227211" forKey:@"longitude"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
        }
        else if(_iHotType==HOTTICKET)
        {
            NSURL *url = [NSURL URLWithString:url_hotTicketList];
            reqSearch=[ASIFormDataRequest requestWithURL:url];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",pageIndex] forKey:@"pageIndex"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance]getCityId]] forKey:@"cityID"];
            if (areaId != 0)
                [reqSearch setPostValue:[NSString stringWithFormat:@"%d",areaId] forKey:@"areaID"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",typeId] forKey:@"merchantType"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%d",orderByType] forKey:@"orderBy"];
            //[reqSearch setPostValue:@"31.853357" forKey:@"latitude"];
            //[reqSearch setPostValue:@"117.227211" forKey:@"longitude"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
            [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
        }
        [reqSearch setDidFinishSelector:@selector(finishSearch:)];
        [reqSearch setShouldAttemptPersistentConnection:NO];
        
        if(!loadingView.bFirstRequest)
        {
            [reqSearch startAsynchronous];
        }

        [reqSearch setDelegate: self];
        isSearchFinished = false;
        [tableDataArray removeAllObjects];
        [mainTable reloadData];
        
    }
    @catch (NSException *exception) {
        NSLog(@"%@",exception.reason);
    }
    @finally {
        
    }
}

//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishSearch:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    if ([dic valueForKey:@"data"]==[NSNull null]) {
        [OMGToast showWithText:search_empty_msg bottomOffset:100];
        tableDataArray=nil;
    }
    else
    {
        returnCount = [tableDataArray count];
    }
    if (returnCount==0) {
        [OMGToast showWithText:search_empty_msg bottomOffset:100];
    }
    delegate=self;
    
    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable];
    isSearchFinished = true;
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedDescription]);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    
    isSearchFinished = true;
    isSearchMoreFinished = true;
    isCuisineFinished = true;
    isAreaFinished = true;
    isConsumeFinished=true;
    
}

- (void) getCuisine
{
    NSURL *url = [NSURL URLWithString:url_cuisineListWithType];
    reqCuisine = [ASIHTTPRequest requestWithURL:url];
    [reqCuisine setDidFinishSelector:@selector(finishCuisine:)];
    [reqCuisine setShouldAttemptPersistentConnection:NO];
    
    if (!loadingView.bFirstRequest)
    {
        [reqCuisine startAsynchronous];
    }

    reqCuisine.delegate = self;
    isCuisineFinished = false;
    
}
- (void)finishCuisine:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    arrayCuisineType = [[NSMutableArray alloc]init];
    for (int i=0;i<data.count;i++) {
        NSDictionary *dic = [data objectAtIndex:i];
        NSString *cuisine = [dic valueForKey:@"cuisinesType"];
        NSString *cuisineCode=[[cuisine componentsSeparatedByString:@"-"] objectAtIndex:0];
        NSString *cuisineName=[[cuisine componentsSeparatedByString:@"-"]objectAtIndex:1];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              cuisineCode,@"cuisineCode",cuisineName,@"cuisineName",[dic valueForKey:@"cuisinesList"],@"cuisinesList",nil];
        [arrayCuisineType insertObject:dict atIndex:i];
    }
    //默认全部
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"cuisineID",@"全部菜系",@"cuisineName",nil];
    arrayCuisine = [[NSMutableArray alloc]init];
    [arrayCuisine insertObject: dict atIndex:0];
    NSDictionary *all = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"0",@"cuisineCode",@"全部菜系",@"cuisineName",arrayCuisine,@"cuisinesList",nil];
    [arrayCuisineType insertObject: all atIndex:0];
    isCuisineFinished = true;
    
}
- (void) getArea{
    //异步请求
    cityId = [[Config Instance]getCityId];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?cityID=%d",url_areaWithDistrict,cityId]] ;
    reqArea = [ASIHTTPRequest requestWithURL:url];
    [reqArea setDidFinishSelector:@selector(finishArea:)];
    isAreaFinished = false;
    [reqArea setShouldAttemptPersistentConnection:NO];
    [reqArea setDelegate: self];
    if (!loadingView.bFirstRequest)
    {
        [reqArea startAsynchronous];
    }
    

}
- (void)finishArea:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    arrayDistrict = [[NSMutableArray alloc]init];
    for (int i=0;i<data.count;i++) {
        NSDictionary *dic = [data objectAtIndex:i];
        NSString *county = [dic valueForKey:@"county"];
        NSString *countyCode=[[county componentsSeparatedByString:@"-"] objectAtIndex:0];
        NSString *countyName=[[county componentsSeparatedByString:@"-"] objectAtIndex:1];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              countyCode,@"countyCode",countyName,@"countyName",[dic valueForKey:@"areaList"],@"areaList",nil];
        [arrayDistrict insertObject:dict atIndex:i];
    }
    //默认全部
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"areaID",@"全部商圈",@"areaName",nil];
    arrayArea = [[NSMutableArray alloc]init];
    [arrayArea insertObject: dict atIndex:0];
    NSDictionary *all = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"0",@"countyCode",@"全部商圈",@"countyName",arrayArea,@"areaList",nil];
    [arrayDistrict insertObject: all atIndex:0];
    isAreaFinished = true;
    if(areaId!=0)
    {
        [self calDefualtArea];
    }
    //areaId = 0;
}

-(void) calDefualtArea
{
    for (int i=0; i<arrayDistrict.count; i++) {
        arrayArea = [[arrayDistrict objectAtIndex: i] objectForKey:@"areaList"];
        for (int j=0; j<arrayArea.count; j++) {
            NSDictionary *area = [arrayArea objectAtIndex:j];//arrayArea[j];
            if ([[area objectForKey:@"areaID" ]intValue]==areaId ){
                _selectedIndex=j;
                _selectedTypeIndex=i;
                break;
            }
        }
        
    }
}

- (void) getCounsume{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_avgConsumeList];
    reqConsume = [ASIHTTPRequest requestWithURL:url];
    [reqConsume setDidFinishSelector:@selector(finishConsume:)];
    isConsumeFinished = false;
    [reqConsume setShouldAttemptPersistentConnection:NO];
    [reqConsume setDelegate: self];
    [reqConsume startAsynchronous];
}
- (void)finishConsume:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayConsume = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"avgConsumeID",@"不限",@"avgConsume",nil];
    [arrayConsume insertObject: dict atIndex:0];
    isConsumeFinished = true;
}

- (void)dealloc
{
    NSLog(@"%@", @"HotsearchView");
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    wqTable = nil;
    [self setLbAddress:nil];
    [self setBtCuisine:nil];
    [self setControlView:nil];
    [self setBtnType:nil];
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_iHotType==HOTCARD)
    {
        if([indexPath row] < ([tableDataArray count])) {
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            float h=[self calculateTextHeight:240 Content:@"1" FontSize:15];
            float height=[self calculateTextHeight:240 Content:[item valueForKey:@"discountInfo"] FontSize:15]-h;
            height=80+height+[self calculateTextHeight:180 Content:[item valueForKey:@"cuisine"]==[NSNull null]?@"1":[item valueForKey:@"cuisine"] FontSize:13]-[self calculateTextHeight:240 Content:@"1" FontSize:13];
            return height;
        }else{
            return 40;
        }
    }
    else if(_iHotType==HOTTICKET)
    {
        return 70;
    }
    else
    {
        if([indexPath row] < ([tableDataArray count])) {
            return 90;
        }else{
            return 40;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"SearchCellIdentifier";
    
    if([indexPath row] < ([tableDataArray count])) {
        if(_iHotType==HOTCARD)
        {
            CellIdentifier = @"CardCellIdentifier";
            CardCell *cell = (CardCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CardCell" owner:nil options:nil];
                cell = [array objectAtIndex:0];
                [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
            }
            
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            cell.lbName.text=[item valueForKey:@"name"];
            cell.lbDiscount.text=[item valueForKey:@"discountInfo"];
            cell.lbDiscount.numberOfLines=0;
            cell.lbDiscount.frame=CGRectMake(cell.lbDiscount.frame.origin.x, cell.lbDiscount.frame.origin.y, 240, 100);
            [cell.lbDiscount sizeToFit];
            cell.lbArea.text=[item valueForKey:@"areaName"];
            cell.lbArea.frame=CGRectMake(cell.lbDiscount.frame.origin.x, cell.lbDiscount.frame.origin.y+cell.lbDiscount.frame.size.height+5, cell.lbArea.frame.size.width, cell.lbArea.frame.size.height);
            [cell.lbArea sizeToFit];
            cell.lbCuisine.text=[item valueForKey:@"cuisine"]==[NSNull null]?@"":[item valueForKey:@"cuisine"];
            cell.lbCuisine.numberOfLines=0;
            cell.lbCuisine.frame=CGRectMake(cell.lbArea.frame.origin.x+cell.lbArea.frame.size.width+10, cell.lbArea.frame.origin.y, 180, cell.lbCuisine.frame.size.height);
            [cell.lbCuisine sizeToFit];
            int dis=[item valueForKey:@"distance"]==[NSNull null]?10000:[[item valueForKey:@"distance"] intValue];
            if(dis<1000)
            {
                cell.lbDistance.text=[NSString stringWithFormat:@"%dm",dis];
            }else if(dis>=1000 && dis<=50000)
            {
                cell.lbDistance.text=[NSString stringWithFormat:@"%.1fkm",dis*1.0/1000];
            }
            else
            {
                cell.lbDistance.text=@"";
            }
            return cell;
        }
        else if(_iHotType==HOTTICKET)
        {
            CellIdentifier = @"TicketCellIdentifier";
            TicketCell *cell = (TicketCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TicketCell" owner:nil options:nil];
                cell = [array objectAtIndex:0];
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            }
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            //cell.contentView.backgroundColor=[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            if([item[@"merchantTypeID"] intValue]==1 )
            {
                cell.ImageType.image=[UIImage imageNamed:@"icon_food.png"];
            }
            else if([item[@"merchantTypeID"] intValue]==2)
            {
                cell.ImageType.image=[UIImage imageNamed:@"icon_ktv.png"];
            }
            else if ([item[@"merchantTypeID"] intValue]==3)
            {
                cell.ImageType.image=[UIImage imageNamed:@"icon_tea.png"];
            }
            cell.lbName.text=item[@"merchantName"];
            cell.lbTitle.text=item[@"title"];
            cell.lbCount.text=[NSString stringWithFormat:@"下载次数:%d",[item[@"downloadNum"] intValue]];
            NSString *endTime=item[@"endDate"];
            cell.lbTime.text=[NSString stringWithFormat:@"有效期：%@",endTime];
            int dis=item[@"distance"]==[NSNull null]?100000:[item[@"distance"] intValue];
            if(dis<1000)
            {
                cell.lbDistance.text=[NSString stringWithFormat:@"%dm",dis];
            }else if(dis>=1000 && dis<=50000)
            {
                cell.lbDistance.text=[NSString stringWithFormat:@"%.1fkm",dis*1.0/1000];
            }
            else
            {
                cell.lbDistance.text=@"";
            }
            return cell;
            
        }
        else
        {
            SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
                cell = [array objectAtIndex:0];
                [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
            }
            
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            //        NSLog(@"%@",item);
            
            cell.name = [item valueForKey:@"name"];
            cell.address = [item valueForKey:@"address"] ;
            cell.distance = ([item valueForKey:@"distance"] ==[NSNull null])?@"" : [NSString stringWithFormat:@"%f",[[item valueForKey:@"distance"] floatValue] ];
            if([item valueForKey:@"cuisine"] !=[NSNull null] || [item valueForKey:@"areaName"] !=[NSNull null])
            {
                cell.cuisine = [item valueForKey:@"cuisine"] ==[NSNull null]?[item valueForKey:@"areaName"] : [item valueForKey:@"cuisine"];
            }
            else
            {
                cell.cuisineLable.hidden=YES;
            }
            cell.discount = [item valueForKey:@"discount"] ==[NSNull null]?@"10":[[item valueForKey:@"discount"]stringValue];
            cell.score = [item valueForKey:@"score"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"score"] floatValue]];
            cell.boxes = ([item valueForKey:@"boxs"]==[NSNull null])?0: [[item valueForKey:@"boxs"] intValue];
            if(typeId==1)
            {
                cell.boxLabel.hidden=NO;
            }else
            {
                cell.boxLabel.hidden=YES;
            }
            
            cell.agree = [[item valueForKey:@"isAgreement"] intValue];
            
            //        显示图片
            NSString * imageStr = [[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"image"];
            NSString *imageName =@"";
            if (![imageStr isEqual:[NSNull null] ]) {
                NSArray *array = [imageStr componentsSeparatedByString:@"/"];
                imageName = [array lastObject];
            }
            NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
            if (image) {
                cell.imageView.image = image;
            }
            else
            {
                cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
                //placeholder为在未加载完成加载图片时显示的默认图片
            }
            if([item valueForKey:@"isCard"]!=[NSNull null] && [[item valueForKey:@"isCard"] intValue]==1)
            {
                cell.imageCard.hidden=NO;
            }
            else
            {
                cell.imageCard.hidden=YES;
            }
            if([item valueForKey:@"isCoupon"]!=[NSNull null] && [[item valueForKey:@"isCoupon"] intValue]==1)
            {
                cell.imageTicket.hidden=NO;
            }
            else
            {
                cell.imageTicket.hidden=YES;
            }
            
            return cell;
        }
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
        
    }
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        if(image)
        {
            cell.imageView.image = image;
        }
    });
    //    cell.imageView.image = image;
    //    cell.imageView.image = [image copy];
    
}

- (IBAction)doBack:(id)sender {
    
    if(!isAreaFinished){
        [reqArea clearDelegatesAndCancel];
        [reqArea cancel];
    }if(!isCuisineFinished){
        [reqCuisine clearDelegatesAndCancel];
        [reqCuisine cancel];
    }if(!isSearchFinished){
        [reqSearch clearDelegatesAndCancel];
        [reqSearch cancel];
    }if(!isSearchMoreFinished){
        [reqSearchMore clearDelegatesAndCancel];
        [reqSearchMore cancel];
    }
    
    // self.bExit=YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showCuisine:(id)sender {
    if(!isShowed){
        selectIndex = 3;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择菜系" options:arrayCuisine types:arrayCuisineType fullHeight:20];
        lplv.name = @"cuisineName";
        lplv.typeName = @"cuisineName";
        lplv.listName = @"cuisinesList";
        lplv.selectedTypeIndex = _selectedTypeIndex1;
        lplv.selectedIndex = _selectedIndex1;
        lplv.delegate = self;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        
        if(_iHotType==HOTHOT || _iHotType==HOTRECOMMAND)
        {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",_iHotType==HOTHOT?url_hotList:url_recommandList,++pageIndex]] ;
            reqSearchMore = [ASIFormDataRequest requestWithURL:url];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getCityId] ] forKey:@"cityID"];
            
            if (cuisineId != 0)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",cuisineId] forKey:@"cuisineID"];
            if (areaId != 0)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",areaId] forKey:@"areaID"];
            if(avgConsumeID != 0)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",avgConsumeID] forKey:@"avgConsumeID"];
            if(typeId!=1 && score!=0)
            {
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",score] forKey:@"score"];
            }
            if(_iViewMerchantType==MERCHANTCARD)
            {
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",1] forKey:@"isCard"];
            }
            else if(_iViewMerchantType==MERCHANTTICKET)
            {
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",1] forKey:@"isCoupon"];
            }
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",typeId] forKey:@"merchantType"];
        }
        else if(_iHotType==HOTTICKET)
        {
            NSURL *url = [NSURL URLWithString:url_hotTicketList];
            reqSearchMore=[ASIFormDataRequest requestWithURL:url];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",++pageIndex] forKey:@"pageIndex"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance]getCityId]] forKey:@"cityID"];
            if (areaId != 0)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",areaId] forKey:@"areaID"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",typeId] forKey:@"merchantType"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",orderByType] forKey:@"orderBy"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
            
        }
        else if(_iHotType==HOTCARD)
        {
            NSURL *url = [NSURL URLWithString:url_cardList];
            reqSearchMore=[ASIFormDataRequest requestWithURL:url];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",++pageIndex] forKey:@"pageIndex"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance]getCityId]] forKey:@"cityID"];
            if (cuisineId != 0 && typeId==1)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",cuisineId] forKey:@"cuisineID"];
            if (areaId != 0)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",areaId] forKey:@"areaID"];
            if(avgConsumeID != 0 && typeId==1)
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",avgConsumeID] forKey:@"avgConsumeID"];
            if(typeId!=1 && score!=0)
            {
                [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",score] forKey:@"score"];
            }
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",typeId] forKey:@"merchantType"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",orderByType] forKey:@"orderBy"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
            
        }
        [reqSearchMore setDidFinishSelector:@selector(appendTableWith:)];
        [reqSearchMore setShouldAttemptPersistentConnection:NO];
        reqSearchMore.delegate = self;
        isSearchMoreFinished = false;
        [reqSearchMore startAsynchronous];
        return;
    }else{
        if(_iHotType==HOTCARD)
        {
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            //            if([[item objectForKey:@"publish"] intValue]==0)
            //            {
            //                [OMGToast showWithText:@"该会员卡商户已关闭" bottomOffset:100];
            //                return;
            //            }
            CardDetailViewController *view=[[CardDetailViewController alloc] initWithNibName:@"CardDetailViewController" bundle:nil];
            view.hidesBottomBarWhenPushed=YES;
            view.settingID=[[item objectForKey:@"settingID"] intValue];
            view.ParView=self.view;
            [self.navigationController pushViewController:view animated:YES];
        }
        else if(_iHotType==HOTTICKET)
        {
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            TicketDetailViewController *view=[[TicketDetailViewController alloc] initWithNibName:@"TicketDetailViewController" bundle:nil];
            view.hidesBottomBarWhenPushed=YES;
            view.merchantTypeID=[[item objectForKey:@"merchantTypeID"] intValue];
            view.couponID=[[item objectForKey:@"couponID"] intValue];
            [self.navigationController pushViewController:view animated:YES];
        }
        else
        {
            RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
            //传递商户id参数
            NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
            SearchCell *cell=(SearchCell *)[tableView cellForRowAtIndexPath:indexPath];
            view.distance = [cell.distanceLable.text copy];
            view.merchantId =[[item objectForKey:@"ID"] intValue];
            view.merchantType=typeId;
            view.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:view animated:YES];
        }
        
    }
    
}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    isSearchMoreFinished = true;
}

- (IBAction)showArea:(id)sender {
    if(!isShowed){
        selectIndex = 2;
        arrayArea = [[arrayDistrict objectAtIndex:  _selectedTypeIndex] objectForKey:@"areaList"];
        
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择商圈" options:arrayArea types:arrayDistrict fullHeight:20];
        lplv.name = @"areaName";
        lplv.typeName = @"countyName";
        lplv.listName = @"areaList";
        lplv.selectedTypeIndex = _selectedTypeIndex;
        lplv.selectedIndex = _selectedIndex;
        lplv.delegate = self;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }
}

- (IBAction)showType:(id)sender {
    selectIndex=6;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择类型" options:arrayType fullHeight:100];
    lplv.name = @"arrayType";
    lplv.selectedIndex = _selectedIndex4;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
    
}

- (IBAction)showTypeTicket:(id)sender {
    selectIndex=10;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择类型" options:arrayTypeTicket fullHeight:100];
    lplv.name = @"arrayTypeTicket";
    lplv.selectedIndex = _selectedIndex4;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
    
}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    switch (selectIndex) {
            //        case 1:{
            //            orderBy = [[arrayOrderBy objectAtIndex:anIndex] objectForKey:@"id"];
            //            break;
            //        }
        case 2:{
            _selectedIndex = anIndex;
            _selectedTypeIndex = anTypeIndex;
            
            _lbSecond.text = [NSString stringWithFormat:@"%@",[[_options objectAtIndex:anIndex] objectForKey:@"areaName"]];
            
            areaId = [[[_options objectAtIndex:anIndex] objectForKey:@"areaID"] intValue];
            break;
        }
        case 3:{
            _selectedIndex1 = anIndex;
            _selectedTypeIndex1 = anTypeIndex;
            arrayCuisine = [_options copy];
            _lbThird.text = [NSString stringWithFormat:@"%@",[[_options objectAtIndex:anIndex] objectForKey:@"cuisineName"]];
            
            cuisineId = [[[_options objectAtIndex:anIndex] objectForKey:@"cuisineID"] intValue];
            break;
        }
        case 5:{
            _selectedIndex3 = anIndex;
            // if (_selectedIndex3==0)
            //_lbConsume.text = AVG_CONSUME;
            // else
            // _lbConsume.text = [NSString stringWithFormat:@"%@",[[arrayConsume objectAtIndex:anIndex] objectForKey:@"avgConsume"]];
            avgConsumeID = [[[arrayConsume objectAtIndex:anIndex] objectForKey:@"avgConsumeID"] intValue];
            break;
        }
        case 6:
        {
            _selectedIndex4=anIndex;
            _lbFirst.text=[[arrayType objectAtIndex:anIndex] objectForKey:@"arrayType"];
            typeId=anIndex+1;
            if(_iHotType==HOTCARD || _iHotType==HOTTICKET)
            {
                break;
            }
            if(anIndex==1  ||  anIndex==2)
            {
                _lbThird.text=@"评分";
                [_btnThird removeTarget:self action:@selector(showCuisine:) forControlEvents:UIControlEventTouchUpInside];
                [_btnThird addTarget:self action:@selector(showScore:) forControlEvents:UIControlEventTouchUpInside];
            }else if(anIndex==0)
            {
                _lbThird.text=[NSString stringWithFormat:@"%@",[[arrayCuisine objectAtIndex:anIndex] objectForKey:@"cuisineName"]];
                [_btnThird removeTarget:self action:@selector(showScore:) forControlEvents:UIControlEventTouchUpInside];
                [_btnThird addTarget:self action:@selector(showCuisine:) forControlEvents:UIControlEventTouchUpInside];
            }
            break;
        }
        case 7:
        {
            _selectedIndex5=anIndex;
            if(anIndex==0)
            {
                score=0;
            }
            else
            {
                score=-1*anIndex+6;
            }
            break;
        }
        case 8:
        {
            [ _BtnType setTitle:[[arrayMerchant objectAtIndex:anIndex] objectForKey:@"arrayMerchant"] forState:UIControlStateNormal];
            if(anIndex==0)
            {
                _iViewMerchantType=MERCHANTALL;
            }
            else if(anIndex==1)
            {
                _iViewMerchantType=MERCHANTCARD;
            }
            else if(anIndex==2)
            {
                _iViewMerchantType=MERCHANTTICKET;
            }
            break;
        }
        case 9:
        {
            _selectedIndex6=anIndex;
            orderByType=anIndex+1;
            _lbThird.text=[[arrayOrderBy objectAtIndex:anIndex] objectForKey:@"arrayOrderBy"];
            break;
        }
        case 10:
        {
            _selectedIndex4=anIndex;
            _lbFirst.text=[[arrayTypeTicket objectAtIndex:anIndex] objectForKey:@"arrayTypeTicket"];
            typeId=anIndex;
            break;
        }
    }
    pageIndex = 1;
    isShowed = false;
    [self getSearchResult];
    
}
- (void)leveyPopListViewDidCancel
{
    //edtCity.text = @"You have cancelled";
    isShowed = false;
}
- (IBAction)showMap:(id)sender {
    MapResultViewController  *view = [[MapResultViewController alloc] initWithNibName:@"MapResultViewController" bundle:nil];
    //    view.results = tableDataArray;
    //    [self.view addSubview:view.view];
    [view.view setFrame:self.view.bounds];
    [view resetAnnitations:tableDataArray];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)OnClickType:(id)sender {
    if(!isShowed){
        selectIndex=8;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择类型" options:arrayMerchant fullHeight:100];
        lplv.name = @"arrayMerchant";
        lplv.selectedIndex = _iViewMerchantType;
        lplv.delegate = self;
        [lplv showInView:self.view animated:YES];
        isShowed=true;
    }
}

-(IBAction)showScore:(id)sender
{
    if(!isShowed){
        selectIndex = 7;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择评分" options:arrayScore fullHeight:100];
        lplv.name = @"arrayScore";
        lplv.selectedIndex = _selectedIndex5;
        lplv.delegate = self;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }
    
}

-(IBAction)showOrderBy:(id)sender
{
    if(!isShowed){
        selectIndex = 9;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择排序" options:arrayOrderBy fullHeight:100];
        lplv.name = @"arrayOrderBy";
        lplv.selectedIndex = _selectedIndex6;
        lplv.delegate = self;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }
    
}

-(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent FontSize:(int)fontsize{
    CGSize constraint = CGSizeMake(widthInput, 20000.0f);
    CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:fontsize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    //CGFloat height = MAX(size.height, 44.0f);
    return size.height;
}

@end